package com.baidumap.administrator.happystudy.module.fenlei.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ab.http.OnMessageResponse;
import com.ab.util.AbFileUtil;
import com.ab.util.AbJsonUtil;
import com.ab.util.ToastUtil;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.ui.GoodDetailActivity;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseFragment;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.module.fenlei.model.Category;
import com.baidumap.administrator.happystudy.module.fenlei.model.CategoryMenu;
import com.baidumap.administrator.happystudy.module.fenlei.model.IndexProducts;
import com.baidumap.administrator.happystudy.module.fenlei.view.ListViewForScrollView;
import com.baidumap.administrator.happystudy.module.search.SearchActivity;
import com.baidumap.administrator.happystudy.utils.UILUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 描述：
 * 作者：xiaoxing on 17/4/18 16:02
 * 邮箱：2235445233@qq.com
 */
public class FenLeiAllFragment extends AppBaseFragment implements OnMessageResponse {

    private ArrayList<CategoryMenu> menuList = new ArrayList<CategoryMenu>();
    private List<CategoryMenu.CategoryItem> categoryitem;
    private View layout;
    private CategoryListAdapter mListAdapter;
    private CategoryGridAdapter mGridAdapter;
    private int selectedPosition;
    private int mSelectedPosition;
    @Bind(R.id.scrollView_category)
    ScrollView mScrollView;

    @Bind(R.id.listView_category)
    ListViewForScrollView listView;

    @Bind(R.id.gridView1)
    GridView gridView;

    public static TextView toolbar_title;
    @Bind(R.id.progressBar1)
    ProgressBar progressBar1;

    @Bind(R.id.img_banner)
    ImageView img_banner;

    private int[] imgBanners = {R.mipmap.fenlei_001, R.mipmap.fenlei_002, R.mipmap.fenlei_003, R.mipmap.fenlei_004, R.mipmap.fenlei_005, R.mipmap.fenlei_006};

    @Override

    public int bindLayout() {
        return R.layout.activity_fen_lei_all;
    }


    @Override
    public void initView(View view, LayoutInflater inflater) {
        super.initView(view, inflater);
//        initData1();
        initListView();
        initGridView();

        toolbar_title = (TextView) view.findViewById(R.id.toolbar_title);
        img_banner.setBackground(getResources().getDrawable(imgBanners[0]));
    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        progressBar1.setVisibility(View.GONE);

        getCategoryMenu();
    }


    @Override
    public void initData() {
        super.initData();

    }

    private void getBundleValue() {
        Bundle bundle = getActivity().getIntent().getExtras();
        if (bundle != null) {
            mSelectedPosition = bundle.getInt("selectedPosition");

        }
    }

    /**
     * 获取菜单数据
     */
    private void getCategoryMenu() {
        menuList.clear();

        Api.indexCategory(this);
    }

    private void getCategoryProduct(String type_id) {
        menuList.clear();

        Api.indexCategoryroducts(this, type_id);

    }

    /**
     * 解析JsonArray获取菜单数据
     */
    private void initData1() {

        String goods_list_menu = AbFileUtil.readAssetsByName(getActivity(), "goods_list_menu.json", "UTF-8");
        ArrayList<CategoryMenu> list = AbJsonUtil.fromJsonArray(goods_list_menu, CategoryMenu.class);
        menuList.addAll(list);

    }

    private void initListView() {
        mListAdapter = new CategoryListAdapter();
        listView.setAdapter(mListAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                mSelectedPosition = 0;
                if (selectedPosition == position) {
                    return;
                }
                getCategoryProduct(mContentBeanList_0.get(position).getType_id());
                mScrollView.smoothScrollTo(0, position * view.getHeight());
                selectedPosition = position;
                if (position < 6) {

//                    ToastUtil.showMessage(getActivity(), position + "");
                    img_banner.setBackground(getResources().getDrawable(imgBanners[position]));
                }
//                mListAdapter.notifyDataSetChanged();
//                mGridAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initGridView() {
        mGridAdapter = new CategoryGridAdapter();
        gridView.setAdapter(mGridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
//
//                LoadingDialogUtil.showGifdialog(getActivity());
                Bundle bundle = new Bundle();

                bundle.putString("product_id", categoryitem.get(position).getCat_id());

                startBundleActivity(bundle, GoodDetailActivity.class);
            }
        });
    }

    private List<Category.DataBean> mContentBeanList_0;
    private int contentBeenListSize_0 = 0;

    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        if (url.equals(Constant.INDEX_CATEGORY) && jo != null) {
            Category category = new Category(jo.toString());

            if (category != null) {


                if (category.getCode().equals("200")) {

                    //一级分类
                    List<Category.DataBean> dataBeanList = category.getData();

                    if (mSelectedPosition > 0) {
                        //点击list时
                        selectedPosition = mSelectedPosition;
                        getCategoryProduct(mContentBeanList_0.get(selectedPosition).getType_id());
                    } else {
                        mContentBeanList_0 = dataBeanList; //临时存储一级分类
                        contentBeenListSize_0 = dataBeanList.size(); //临时存储一级分类的大小
                        getCategoryProduct(dataBeanList.get(0).getType_id());

                    }


                } else {
                    ToastUtil.showMessage(getActivity(), category.getMsg());
                }
            }

        }
        if (url.equals(Constant.INDEX_PRODUCTS) && jo != null) {
            IndexProducts indexProducts = new IndexProducts(jo.toString());

            if (indexProducts != null) {


                if (indexProducts.getCode().equals("200")) {

                    //二级分类
                    List<IndexProducts.DataBean> dataBeanList = indexProducts.getData();


                    ArrayList<CategoryMenu> list = new ArrayList<>();
                    //gridiew分类，二级分类，parentid不为0
                    for (int i = 0; i < contentBeenListSize_0; i++) {

                        CategoryMenu categoryMenu = new CategoryMenu();
                        categoryMenu.setCategory(mContentBeanList_0.get(i).getType_name());

                        List<CategoryMenu.CategoryItem> categoryItemList = new ArrayList<>();


                        for (int k = 0; k < dataBeanList.size(); k++) {
                            List<CategoryMenu.CategoryItem.Menu> categoryItemMenuList = new ArrayList<>();

                            CategoryMenu.CategoryItem categoryItem = categoryMenu.new CategoryItem();

                            categoryItem.setCat_id(dataBeanList.get(k).getProduct_id());
                            categoryItem.setTypename(dataBeanList.get(k).getProduct_name());
                            categoryItem.setImgurl(dataBeanList.get(k).getProduct_pic1());

                            categoryItem.setMenu(categoryItemMenuList);
                            categoryItemList.add(categoryItem);
                        }
                        categoryMenu.setCategoryitem(categoryItemList);

                        list.add(categoryMenu);

                    }

                    menuList.clear();
                    menuList.addAll(list);

                    mListAdapter.notifyDataSetChanged();
                    mGridAdapter.notifyDataSetChanged();
                } else {

                }
            }

        }

    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.search)
    public void onClick() {

        startActivity(SearchActivity.class);
    }

    class CategoryListAdapter extends BaseAdapter {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = getActivity().getLayoutInflater().inflate(
                    R.layout.item_category_list, null);
            TextView tvCategoryList = (TextView) inflate
                    .findViewById(R.id.tv_category_list);
            inflate.setTag(tvCategoryList);
            String categoryType = menuList.get(position).getCategory();
            tvCategoryList.setText(categoryType);
            if (selectedPosition == position) {
                inflate.setBackgroundResource(R.drawable.drawable_common_category_list_s);
                tvCategoryList.setTextColor(getResources()
                        .getColor(R.color.fen_lei_selected));
            } else {
                inflate.setBackgroundResource(R.drawable.drawable_common_category_list);
                tvCategoryList.setTextColor(getResources().getColor(
                        R.color.fen_lei_normal));

            }

            return inflate;
        }

        @Override
        public int getCount() {
            return menuList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

    }

    class CategoryGridAdapter extends BaseAdapter {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = null;
            GridViewHolder holder = null;
            if (convertView == null) {
                holder = new GridViewHolder();
                inflate = getActivity().getLayoutInflater().inflate(
                        R.layout.item_category_grid, null);
                holder.imgCategoryGrid = (ImageView) inflate
                        .findViewById(R.id.img_category_grid);
                holder.tvCategoryGrid = (TextView) inflate
                        .findViewById(R.id.tv_category_grid);
                inflate.setTag(holder);
            } else {
                inflate = convertView;
                holder = (GridViewHolder) inflate.getTag();
            }


            holder.tvCategoryGrid.setText(menuList.get(selectedPosition)
                    .getCategoryitem().get(position).getTypename());
            UILUtils.displayImage(getActivity(), menuList.get(selectedPosition)
                    .getCategoryitem().get(position).getImgurl(), holder.imgCategoryGrid);
            return inflate;
        }

        @Override
        public int getCount() {
            if (menuList.size() > 0) {
                categoryitem = menuList.get(selectedPosition).getCategoryitem();

                return categoryitem.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

    }

    class GridViewHolder {
        ImageView imgCategoryGrid;
        TextView tvCategoryGrid;
    }

}
